﻿using System;
using System.Collections.Generic;
using System.Text;
using com.yoozoo.gta.Gameplay.PVE;
using ImageEffects;
using OWL.Rendering.HRP;
using UnityEngine;
using UnityEngine.Profiling;
using XLua;
using Yoozoo.Core.Common;
using Yoozoo.Framework.Core;
using Yoozoo.Gameplay.RTS;
using Yoozoo.Gta.Common;
using Yoozoo.Managers.ResourceManagerV2.Framework;
using Yoozoo.Mars.Got;

namespace Gameplay.PVE.Survivor
{
    public class SurvivorManager: MonoBehaviour
    {
        public Transform Root;

        private static SurvivorManager instance;

        public static bool isTest = true;
        public static bool isNoDamage = false;
        public static bool selfNoDamage = false;
        public static bool selfDamageUp = false;
        public static bool isUnitRendering = true;
        public static bool isNavmeshActive = true;
        public static bool skipTimeline = false;
        public static bool isNavMesh = true;
        public static bool isShowEffect = true;
        public static bool isMap = true;
        public static bool m_isLoadgingTest = false;

        private static bool isLoadingTest
        {
            set
            {
                m_isLoadgingTest = value;
                ResObjectCacheManager.isSlowLoading = value;
            }
            get
            {
                return m_isLoadgingTest;
            }
        }
        
        private static bool m_isProfiler;
        public static bool isProfiler
        {
            set
            {
                m_isProfiler = value;
                BattleDebug.enableProfiler = value;
            }
            get
            {
                return m_isProfiler;
            }
        }
        

        public static bool isMissionActive = true;
        public static bool isEventActive = true;
        public static bool isInteractableActive = true;
        public static bool useMissionHero = true;
        public static bool showCollision = false;
        public static bool isForceDeck = false;

        public static int testSpawnGroupId = 4;
        
        public static int stageId;
        public static int stageSubId;
        public static List<int> initialHeroes = new List<int>();

        public static float dropGravity = 30;
        public static float dropStartHeight = 1;
        public static float dropFlyTime = 0.7f;
        public static float dropSpeed = 2;
        
        public static bool IsInGame = false;

        public static bool isProfiling = true;
        
        public static SurvivorManager Instance
        {
            get
            {
                if (instance == null)
                {
                    var root = new GameObject("SurvivorRoot");
                    instance = root.AddComponent<SurvivorManager>();
                    instance.Root = root.transform;
                }

                return instance;
            }
        }

        public void SetMissionId(int missionId,int subId = 1)
        {
            stageId = missionId;
            stageSubId = subId;
        }
        
		public void Initialize()
        {
            if (IsInGame)
            {
                return;
            }
            IsInGame = true;
            TimeManager.Instance.Initialize();
            GuideLineManager.Instance.Initialize();
            FlyTextManager.Instance.Initialize();
            BattlePoolManager.Instance.Initialize();
            CollisionManager.Instance.Initialize();
            BattleConfigManager.Instance.Initialize();
            BattleResourceManager.Instance.Initialize();
            BattlePropsManager.Instance.Initialize(stageId);
            CameraManager.Instance.Initialize();
            MapManager.Instance.Initialize();
            StageManager.Instance.Initialize(stageId,stageSubId);
            //GPUInstancingManager.SetSurvivorPath();
            GPUInstancingManager.isSurvivor = true;
            //根据画质，设置关键字
            #if !UNITY_IOS
            var curSetting = QualityHelper.CurrentAdjusterSetting;
            if (curSetting != null)//high下降一级
            {
                if (curSetting.quality == QualityEnum.VeryHigh)
                {
                    Shader.DisableKeyword(SceneGraphicLevel._SCENE_GRAPHIC_SUPREME.ToString());
                    Shader.EnableKeyword(SceneGraphicLevel._SCENE_GRAPHIC_MEDIUM.ToString());
                }
                else if (curSetting.quality == QualityEnum.High)
                {
                    Shader.DisableKeyword(SceneGraphicLevel._SCENE_GRAPHIC_HIGH.ToString());
                    Shader.EnableKeyword(SceneGraphicLevel._SCENE_GRAPHIC_MEDIUM.ToString());
                }
            }
            #endif
            //TestManager.Instance.Initialize();
        }

        private string GetFileName(string name)
        {
            int hashCode = Utility.Verifier.GetCrc32(Encoding.UTF8.GetBytes(name));
            string hashCodeString = $"{hashCode:x8}";
            string folder = hashCodeString.Substring(0, 2);

            return $"data/{folder}/{hashCodeString}";
        }

		void Start()
		{
			
		}


        void Update()
        {
            if (!IsInGame)
            {
                return;
            }
            //try
            {
                Profiler.BeginSample("TimeManager.Update");
                TimeManager.Instance.Update();
                Profiler.EndSample();

                DeckManager.Instance.Update();
                StageManager.Instance.PreUpdate();
                if (!StageManager.Instance.IsPause)
                {
                    Profiler.BeginSample("BattleEventManager.Update");
                    BattleEventManager.Instance.Update();
                    Profiler.EndSample();
                
                    Profiler.BeginSample("MissionManager.Update");
                    MissionManager.Instance.Update();
                    Profiler.EndSample();
                
                    Profiler.BeginSample("ControlManager.Update");
                    ControlManager.Instance.Update();
                    Profiler.EndSample();
                
                    Profiler.BeginSample("UnitManager.Update");
                    UnitManager.Instance.Update();
                    Profiler.EndSample();
                
                    Profiler.BeginSample("StageManager.Update");
                    StageManager.Instance.Update();
                    Profiler.EndSample();

                    Profiler.BeginSample("BattleEffectManager.Update");
                    BattleEffectManager.Instance.Update();
                    Profiler.EndSample();
                
                    Profiler.BeginSample("FlyTextManager.Update");
                    FlyTextManager.Instance.Update();
                    Profiler.EndSample();
                }
               
                BattlePropsManager.Instance.Update();
                
                Profiler.BeginSample("BulletManager.Update");
                BulletManager.Instance.Update();
                Profiler.EndSample();
                
                Profiler.BeginSample("MapManager.Update");
                MapManager.Instance.Update();
                Profiler.EndSample();
                
                Profiler.BeginSample("CameraManager.Update");
                CameraManager.Instance.Update();
                Profiler.EndSample();
            }/*catch(Exception e)
            {
                UnityEngine.Debug.LogError(e);
            }*/
            //TestManager.Instance.Update();
        }

        private void LateUpdate()
        {
            if (!IsInGame)
            {
                return;
            }
            if (!StageManager.Instance.IsPause)
            {
                StageManager.Instance.LateUpdate();
                UnitManager.Instance.LateUpdate();
                BattleEffectManager.Instance.LateUpdate();
            }
            CameraManager.Instance.LateUpdate();
        }

        public void ReStart()
        {
            IsInGame = false;
            HeroEventBubbleManager.Instance.Dispose();
            BattlePropsManager.Instance.Dispose();
            GuideLineManager.Instance.Dispose();
            BulletManager.Instance.Dispose();
            UnitManager.Instance.Dispose();
            // BattleConfigManager.Instance.Dispose();
            CameraManager.Instance.Dispose();
            MapManager.Instance.Dispose();
            FlyTextManager.Instance.Dispose();
            TimeManager.Instance.Dispose();
            CollisionManager.Instance.Dispose();
            BattleEventManager.Instance.Dispose();
            MissionManager.Instance.Dispose();
            ControlManager.Instance.Dispose();
            BattleEffectManager.Instance.Dispose();
            StageManager.Instance.Dispose();
            BattlePoolManager.Instance.Dispose();
            BattleResourceManager.Instance.Dispose();
            StatisticManager.Instance.Dispose();
            LightController.ClearGpuSkinningMaterial();
            DeckManager.Instance.Dispose();
            GPUInstancingManager.GetInstance().Dispose();
            GameObject.DestroyImmediate(instance.Root.gameObject);
            this.Initialize();
        }

        public void Dispose()
        {
            if (!IsInGame)
            {
                return;
            }
            IsInGame = false;
            HeroEventBubbleManager.Instance.Dispose();
            BattlePropsManager.Instance.Dispose();
            GuideLineManager.Instance.Dispose();
            BulletManager.Instance.Dispose();
            UnitManager.Instance.Dispose();
            BattleConfigManager.Instance.Dispose();
            CameraManager.Instance.Dispose();
            MapManager.Instance.Dispose();
            FlyTextManager.Instance.Dispose();
            TimeManager.Instance.Dispose();
            CollisionManager.Instance.Dispose();
            BattleEventManager.Instance.Dispose();
            MissionManager.Instance.Dispose();
            ControlManager.Instance.Dispose();
            BattleEffectManager.Instance.Dispose();
            StageManager.Instance.Dispose();
            BattlePoolManager.Instance.Dispose();
            BattleResourceManager.Instance.Dispose();
            StatisticManager.Instance.Dispose();
            LightController.ClearGpuSkinningMaterial();
            DeckManager.Instance.Dispose();
            GPUInstancingManager.GetInstance().Dispose();
            GameObject.DestroyImmediate(instance.Root.gameObject);
            GPUInstancingManager.isSurvivor = false;
            instance = null;
            /*var curSetting = QualityHelper.CurrentAdjusterSetting;
            if (curSetting != null)//还原
            {
                if (curSetting.quality == QualityEnum.VeryHigh)
                {
                    Shader.DisableKeyword(SceneGraphicLevel._SCENE_GRAPHIC_MEDIUM.ToString());
                    Shader.EnableKeyword(SceneGraphicLevel._SCENE_GRAPHIC_SUPREME.ToString());
                }
                else if (curSetting.quality == QualityEnum.High)
                {
                    Shader.DisableKeyword(SceneGraphicLevel._SCENE_GRAPHIC_MEDIUM.ToString());
                    Shader.EnableKeyword(SceneGraphicLevel._SCENE_GRAPHIC_HIGH.ToString());
                }
            }*/
        }

        public void Pause()
        {
            StageManager.Instance.Pause();
        }

        public void Resume()
        {
            StageManager.Instance.Resume();
        }

        public void DeckToBattle()
        {
            DeckManager.Instance.DeckToBattle();
            DeckManager.Instance.ClearBase();
        }

        public void FinishShowTask()
        {
            StageManager.Instance.CheckShowDeck();
        }
        
        private void OnDrawGizmos()
        {
            CollisionManager.Instance.DrawGizmos();
        }
        
        public void Win()
        {
            StageManager.Instance.Win();
        }

        public void Lose()
        {
            StageManager.Instance.Lose();
        }

        public void SwitchToRpg(int levelId)
        {
            Pause();
            StageManager.Instance.isEnd = true;
            ResidentHandler.Inst.GetFunction("L_SurvivorManager.SwitchToRpg").Action(levelId);
        }

        public void ShowGuideDialogue(int dialogueId,Action callback = null)
        {
            Pause();
            ResidentHandler.Inst.GetFunction("L_SurvivorManager.ShowGuideDialogue").Action<int, Action>(dialogueId,
                () =>
                {
                    callback?.Invoke();
                    Resume();
                });
        }
        
        public void ShowTruckTips(bool isShow)
        {
            ResidentHandler.Inst.GetFunction("L_SurvivorManager.ShowRangeTip").Action(isShow == true ? 1 : 0);
        }
        
        public void ChangeHero()
        {
            StageManager.Instance.TeamGroup.ResetHeroes();
        }
    }
}
